package com.example.smartcitydemo.exception

import android.content.Intent
import android.net.ParseException
import android.util.Log
import com.example.smartcitydemo.MyApplication
import com.example.smartcitydemo.receiver.LoginBroadCastReceiver
import com.google.gson.JsonParseException
import com.google.gson.stream.MalformedJsonException
import kotlinx.serialization.SerializationException
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

/**
 * @PACKAGE_NAME: com.example.smartcitydemo.exception
 * @NAME: Caleb.F
 * @DATE: 2021/11/3 10:55
 * @Email: 1919796283@qq.com
 */
class AppExcpetion(val code: Int, val errorMsg: String, val errorCause: Throwable?) : Exception() {
    //次构造器
    constructor(errorEum: ErrorType, errorCause: Throwable?) : this(
        errorEum.code,
        errorEum.msg,
        errorCause
    )

    companion object {
        fun transFormException(e: Throwable): AppExcpetion {
            val ex: AppExcpetion
            when (e) {
                is HttpException, is ConnectException -> {
                    ex = AppExcpetion(
                        ErrorType.NETWORK_ERROR.code, e.message ?: ErrorType.NETWORK_ERROR.msg, e
                    )
                    return ex
                }
                is JsonParseException, is JSONException, is ParseException, is MalformedJsonException -> {
                    ex = AppExcpetion(ErrorType.PARSE_ERROR, e)
                    return ex
                }
                is SerializationException -> {
                    ex = AppExcpetion(
                        ErrorType.PARSE_ERROR.code,
                        e.message ?: "SerializationException",
                        e
                    )
                    return ex
                }
                is SocketTimeoutException -> {
                    ex = AppExcpetion(ErrorType.TIMEOUT_ERROR, e)
                    return ex
                }
                is UnknownHostException -> {
                    ex = AppExcpetion(ErrorType.UNKOWN_HOST_ERROR, e)
                    return ex
                }
                //方便自主构造的异常,code==500,401等
                is AppExcpetion -> return e
                else -> {
                    Log.d("dede", "transFormException: ${e.message}")
                    ex = AppExcpetion(ErrorType.UNKOWN_ERROR, e)
                    return ex
                }
            }
        }


        fun handleException(appException: AppExcpetion) {
            if (appException.code == 1005) {
                val intent =
                    Intent(LoginBroadCastReceiver.LOGIN_RECEIVER_ACTION)
                intent.setPackage(MyApplication.instance.packageName)
                MyApplication.instance.sendBroadcast(intent)
            }
        }

    }
}
